package com.zw.weiyi.avtivity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.AsyncQueryHandler;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.zw.weiyi.adapter.MessageAdapter;
import com.zw.weiyi.enety.Message;
import com.zw.weiyi.phonesms.BaseActivity;
import com.zw.weiyi.phonesms.R;
import com.zw.weiyi.util.MessageUtil;

/**
 * 短信消息列表 收发人
 * 
 * @author Striver_zw Date 2014-12-13
 */
public class MessageBoxList extends BaseActivity implements
		OnItemLongClickListener {
	private ListView talkView;
	private List<Message> messages = null;
	private AsyncQueryHandler asyncQuery;
	private String address;
	private SimpleDateFormat sdf;
	private TextView smsname;
	private ImageButton back;
	private EditText sms_faxin;
	private Button sms_but_fa;
	private MessageAdapter messageAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sms_message_list);

		sdf = new SimpleDateFormat("MM-dd HH:mm");
		String thread = getIntent().getStringExtra("threadId");
		String name = getIntent().getStringExtra("name");

		back = (ImageButton) findViewById(R.id.back);
		sms_but_fa = (Button) findViewById(R.id.sms_but_fa);
		sms_faxin = (EditText) findViewById(R.id.sms_faxin);

		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		sms_but_fa.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String connt = sms_faxin.getText().toString().trim();// 获取短信内容
				MessageUtil.sendMessage(getApplicationContext(), messages
						.get(0).getName(), connt);
				sms_faxin.setText("");
				messages.add(new Message(messages.get(0).getName(), System.currentTimeMillis() + "", connt, 2));
				messageAdapter.notifyDataSetChanged();
			}
		});

		init(thread, name);

	}

	private void init(String thread, String name) {
		asyncQuery = new MessageAsynQueryHandler(getContentResolver());
		talkView = (ListView) findViewById(R.id.message_list);
		smsname = (TextView) findViewById(R.id.smsname);
		messages = new ArrayList<Message>();
		smsname.setText(name);
		talkView.setOnItemLongClickListener(this);
		Uri uri = Uri.parse("content://sms");
		String[] projection = new String[] { "date", "address", "person",
				"body", "type" }; // 查询的列
		asyncQuery.startQuery(0, null, uri, null, "thread_id = " + thread,
				null, "date asc");
	}

	private class MessageAsynQueryHandler extends AsyncQueryHandler {

		public MessageAsynQueryHandler(ContentResolver cr) {
			super(cr);
		}

		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			if (cursor != null && cursor.getCount() > 0) {
				cursor.moveToFirst();
				for (int i = 0; i < cursor.getCount(); i++) {
					cursor.moveToPosition(i);
					String date = sdf.format(new Date(cursor.getLong(cursor
							.getColumnIndex("date"))));
					if (cursor.getInt(cursor.getColumnIndex("type")) == 1) {// 别人发的
						Message d = new Message(
								cursor.getString(cursor
										.getColumnIndex("address")),
								date,
								cursor.getString(cursor.getColumnIndex("body")),
								cursor.getLong(1) + "", cursor.getString(0),
								R.layout.sms_message_you_item);
						messages.add(d);
					} else {// 2 自己发过去的
						Message d = new Message(
								cursor.getString(cursor
										.getColumnIndex("address")),
								date,
								cursor.getString(cursor.getColumnIndex("body")),
								cursor.getLong(1) + "", cursor.getString(0),
								R.layout.sms_message_me_item);
						messages.add(d);
					}
				}
				if (messages.size() > 0) {
					messageAdapter = new MessageAdapter(MessageBoxList.this,
							messages);
					talkView.setAdapter(messageAdapter);
					talkView.setDivider(null);
					talkView.setSelection(messages.size());
				} else {
					Toast.makeText(MessageBoxList.this, "没有短信进行操作",
							Toast.LENGTH_SHORT).show();
				}
			}
			super.onQueryComplete(token, cookie, cursor);
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> adapterView, View view,
			final int position, long id) {
		final Message mb = messages.get(position);
		new AlertDialog.Builder(this)
				.setTitle("信息选项")
				.setItems(new String[] { "复制到文本", "删除该条记录" },
						new DialogInterface.OnClickListener() {
							@SuppressLint("NewApi")
							public void onClick(DialogInterface dialog,
									int which) {
								switch (which) {
								case 0:// 复制到文本
									ClipboardManager cmb = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
									cmb.setText(mb.getText());
									break;

								case 1:
									MessageUtil.deleteMessageChild(getApplicationContext(), mb);
									messages.remove(position);
									messageAdapter.notifyDataSetChanged();
									Toast.makeText(getApplicationContext(),"删除成功", 1000).show();
									break;
								}
							}
						}).show();
		return false;
	}
}
